/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Select, Switch, Image, Modal, message, Popconfirm, Form, Tag } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import {
  setenable,
  role,
  area,
  department,
  deleteuser,
  resetuser,
  userdetail,
} from '@/services/basic';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import Cascader from '@/components/AutoTable/Cascader';
import moment from 'moment';
import ProDescriptions from '@ant-design/pro-descriptions';
import { getFetch } from '@/utils/doFetch';

function mapTree(org) {
  const haveChildren = Array.isArray(org.childrens) && org.childrens.length > 0;
  return {
    //分别将我们查询出来的值做出改变他的key
    title: org.name,
    label: org.name,
    value: org.id,
    //判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
    children: haveChildren ? org.childrens.map((i) => mapTree(i)) : [],
  };
}

function User(props) {
  let actionRef = useRef(),
    ChildRef = null,
    [formRef] = Form.useForm();

  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState({
      name: {
        value: null,
        type: 'input',
        title: '姓名',
        name: ['name'],
        required: true,
      },
      password: {
        value: null,
        type: 'password',
        title: '密码',
        name: ['password'],
        required: true,
      },
      sex: {
        value: null,
        type: 'radio',
        title: '性别',
        name: ['sex'],
        required: true,
        options: [
          {
            label: '男',
            value: '男',
          },
          {
            label: '女',
            value: '女',
          },
        ],
      },
      enable: {
        value: true,
        type: 'radio',
        title: '是否启用',
        name: ['enable'],
        required: true,
        options: [
          {
            label: '启用',
            value: true,
          },
          {
            label: '停用',
            value: false,
          },
        ],
      },
      department_ids: {
        value: [],
        type: 'treeselect',
        title: '部门职位',
        name: ['department_ids'],
        required: true,
        options: {
          database: department,
          params: {},
        },
        multiple: true,
        formart: {
          label: 'name',
          key: 'id',
          children: 'childrens',
        },
        col: { span: 24 }, //栅格布局 默认 12
      },
      roles: {
        value: [],
        type: 'table',
        title: '角色-区域设置',
        name: ['roles'],
        required: true,
        columns: [
          {
            title: '角色',
            dataIndex: 'id',
            key: 'id',
            search: false,
            valueType: 'select',
            width: 200,
            request: async () => {
              const res = await role({ is_all: 1 });
              return res?.data?.dataList?.map((it) => ({
                label: it.name,
                value: it.id,
              }));
            },
            formItemProps: {
              rules: [
                {
                  required: true,
                  message: '此项是必填项',
                },
              ],
            },
          },
          {
            title: '负责区域',
            dataIndex: 'area_ids',
            key: 'area_ids',
            valueType: 'select',
            search: false,
            fieldProps: {
              mode: 'multiple',
            },
            request: async () => {
              const res = await area({ is_all: 1 });
              return res?.data?.dataList?.map((it) => ({
                label: it.name,
                value: it.id,
              }));
            },
            formItemProps: {
              rules: [
                {
                  required: true,
                  message: '此项是必填项',
                },
              ],
            },
          },
          {
            title: '操作',
            valueType: 'option',
            width: 60,
            render: () => {
              return null;
            },
          },
        ],
        rowKey: 'key',
        col: { span: 24 },
      },
      phone: {
        value: null,
        type: 'input',
        title: '手机号',
        name: ['phone'],
        required: true,
      },
      email: {
        value: null,
        type: 'input',
        title: '邮箱',
        name: ['email'],
        required: false,
      },
      entry_time: {
        value: null,
        type: 'datepicker',
        title: '入职日期',
        name: ['entry_time'],
        disabledDate: (current) => {
          return current && current > moment().endOf('day');
        },
        required: false,
      },
      quit_time: {
        value: null,
        type: 'datepicker',
        title: '离职日期',
        name: ['quit_time'],
        disabledDate: (current) => {
          let currents = formRef.getFieldValue('entry_time');
          return current ? current < currents : false;
        },
        required: false,
      },
      contracts: {
        value: null,
        type: 'upload',
        title: '合同附件',
        name: ['contracts'],
        required: false,
        listType: 'img',
        multiple: false,
        limit: 20,
      },

      // description: {
      //     value: null,
      //     type: 'textarea',
      //     title: '备注',
      //     name: ['description'],
      //     required: false,
      //     //serverURL: "https://www.mocky.io/v2/5cc8019d300000980a055e76"//替换为自己的上传地址 富文本图片/附件
      //     col: { span: 24 },//栅格布局 默认 12
      // },
    }),
    [iftype, ciftype] = useState({});

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
        search: false,
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        search: false,
      },
      {
        title: '是否启用',
        dataIndex: 'enable',
        key: 'enable',
        search: false,
        render: (_, record) => {
          return (
            <Switch
              checkedChildren="启用"
              unCheckedChildren="停用"
              checked={record.enable}
              onChange={() => {
                setenable({ id: record.id, enable: !record.enable }).then((res) => {
                  res.code == 0 && reload();
                });
              }}
            />
          );
        },
      },
      {
        title: '管理员',
        dataIndex: 'is_admin',
        key: 'is_admin',
        search: false,
        render: (_, record) => {
          return record.is_admin ? '是' : '否';
        },
      },
      {
        title: '角色',
        dataIndex: 'roles',
        key: 'roles',
        search: false,
        render: (_, record) => {
          return Array.isArray(record.roles)
            ? record.roles.map((it, i) => (
                <Tag key={i} style={{ float: 'left' }}>
                  {it.role_name}
                </Tag>
              ))
            : '-';
        },
      },
      {
        title: '部门职位',
        dataIndex: 'departments',
        key: 'department_id',
        valueType: 'treeSelect',
        fieldProps: {
          treeDefaultExpandAll: true,
        },
        render: (_, record) => {
          return Array.isArray(record.departments)
            ? record.departments.map((it, i) => (
                <Tag color="blue" key={i}>
                  {it.department_name}
                </Tag>
              ))
            : '-';
        },
        request: async () => {
          let res = await getFetch({ url: '/wbn-api/department', params: {} });
          let result = res?.data?.map((it) => mapTree(it)) ?? [];
          return result;
        },
      },
      {
        title: '操作',
        valueType: 'option',
        width: 220,
        fixed: 'right',
        render: (text, record, _) => [
          <a
            style={{ color: '#1890ff' }}
            onClick={() => {
              cvs(true);
              ciftype({
                val: 'detail',
                title: '查看详情',
                curitem: record,
              });
            }}
          >
            详情
          </a>,
          <a
            style={{ color: '#1890ff' }}
            onClick={() => {
              cf((fields) => {
                for (let i in fields) {
                  fields[i].value = record[i];
                  if (i == 'password') {
                    fields[i].hides = true;
                  }
                  if (i == 'department_ids') {
                    fields[i].value = record.departments.map((it) => it.department_id);
                  } else if (i == 'roles') {
                    fields[i].value = record.roles.map((it) => ({
                      ...it,
                      key: it.id,
                      id: it.role_id,
                    }));
                  }
                }
                return { ...fields };
              });
              cvs(true);
              ciftype({
                val: 'edit',
                title: '编辑用户',
                id: record.id,
              });
            }}
          >
            编辑
          </a>,
          <Popconfirm
            placement="bottom"
            title={'确认删除该用户？'}
            onConfirm={() => {
              deleteuser(record.id).then((res) => {
                if (res.code == 0) {
                  message.success('操作成功');
                  reload();
                }
              });
            }}
            okText="删除"
            cancelText="取消"
          >
            <a style={{ color: '#f50' }}>删除</a>
          </Popconfirm>,
          <Popconfirm
            placement="bottom"
            title={'确认重置该用户密码？'}
            onConfirm={() => {
              resetuser({ id: record.id }).then((res) => {
                if (res.code == 0) {
                  message.success('操作成功');
                  reload();
                }
              });
            }}
            okText="确定"
            cancelText="取消"
          >
            <a style={{ color: '#f50' }}>重置密码</a>
          </Popconfirm>,
        ],
      },
    ],
    extracolumns = [
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
        search: false,
      },
      {
        title: '入职时间',
        dataIndex: 'entry_time',
        key: 'entry_time',
        search: false,
      },
      {
        title: '离职时间',
        dataIndex: 'quit_time',
        key: 'quit_time',
        search: false,
      },
      {
        title: '合同',
        dataIndex: 'contracts',
        key: 'contracts',
        render: (_, row) => {
          if (!row.contracts) {
            return (
              <Image
                width={32}
                height={32}
                style={{ padding: 2 }}
                src={require('@/assets/default.png')}
              />
            );
          } else {
            return row.contracts.map((it) => {
              return <Image width={32} height={32} src={it.origin_url} style={{ padding: 2 }} />;
            });
          }
        },
      },
    ];

  let extrarender = [
    <div
      className="action"
      title="新增"
      onClick={() => {
        cvs(true);
        cf((fields) => {
          for (let i in fields) {
            fields[i].value = '';
            fields[i].hides = false;
            if (i == 'enable') {
              fields[i].value = true;
            }
            if (i == 'department_ids') {
              fields[i].value = [];
            }
          }
          return { ...fields };
        });
        ciftype({
          val: 'add',
          title: '新增职员',
        });
      }}
    >
      <PlusOutlined />
    </div>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'basic/adduser',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'edit') {
      dispatch({
        type: 'basic/edituser',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        x={990}
        pagetitle={props.route.name}
        pageextra={extrarender}
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/user"
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
      >
        {iftype.val == 'detail' && iftype.curitem ? (
          <ProDescriptions
            title={`${iftype.curitem.name}的详细信息`}
            columns={[...columns, ...extracolumns]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype.curitem}
          />
        ) : (
          <InitForm
            formRef={formRef}
            fields={fields}
            submitData={(values, fn) => {
              saveData(values, fn);
            }}
            onChange={() => {
              //联动操作
            }}
            submitting={props.loading.effects['basic/adduser'] || !vs}
          />
        )}
      </Modal>
    </div>
  );
}

export default connect(({ basic, loading }) => ({
  basic,
  loading,
}))(User);
